<template>
  <a-modal
    class="image-out-painting"
    v-model:visible="visible"
    title="AI 人像风格重塑"
    :footer="false"
    @cancel="closeModal"
    :centered="true"
    :maskStyle="{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }"
  >
    <div class="content-container">
      <a-row :gutter="[24, 24]" justify="center">
        <!-- 原始图片 -->
        <a-col :span="12" class="image-column">
          <div class="image-container">
            <h4 class="section-title">原始图片</h4>
            <img
              :src="picture?.url"
              :alt="picture?.name"
              class="preview-image"
              @load="onImageLoad"
            />
          </div>
        </a-col>

        <!-- 重塑结果 -->
        <a-col :span="12" class="image-column">
          <div class="image-container">
            <h4 class="section-title">重塑结果</h4>
            <img
              v-if="resultImageUrl"
              :src="resultImageUrl"
              :alt="picture?.name"
              class="preview-image"
              @load="onImageLoad"
            />
            <div v-else class="loading-placeholder">
              <a-spin size="large" />
            </div>
          </div>
        </a-col>
      </a-row>

      <!-- 风格选择 -->
      <div class="style-selector">
        <a-select
          v-model:value="selectedStyleIndex"
          style="width: 100%; margin: 24px 0"
          placeholder="请选择风格"
          :bordered="false"
          size="large"
          class="custom-select"
        >
          <a-select-option
            v-for="(name, index) in styleOptions"
            :key="index"
            :value="index"
          >
            {{ name }}
          </a-select-option>
        </a-select>
      </div>

      <!-- 进度条 -->
      <div v-if="taskId" class="progress-section">
        <a-progress
          :percent="progress"
          :stroke-width="8"
          show-info
          :style="{ marginBottom: '24px' }"
        />
      </div>

      <!-- 操作按钮 -->
      <div class="button-group">
        <a-button
          type="primary"
          :loading="!!taskId"
          ghost
          @click="createTask"
          class="action-btn"
          @mousedown="handleButtonClick"
          @mouseup="handleButtonClick"
        >
          生成图片
        </a-button>
        <a-button
          v-if="resultImageUrl"
          type="primary"
          :loading="uploadLoading"
          @click="handleUpload"
          class="action-btn"
          @mousedown="handleButtonClick"
          @mouseup="handleButtonClick"
        >
          应用结果
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { onUnmounted, ref } from 'vue'
import {
  createImageRestyleTaskUsingPost,
  getImageRestyleTaskUsingGet,
  uploadPictureByUrlUsingPost,
} from '@/api/pictureController'
import { message } from 'ant-design-vue'

const styleOptions: Record<string, string> = {
  '-1': '参考上传图像风格',
  '0': '复古漫画',
  '1': '3D童话',
  '2': '二次元',
  '3': '小清新',
  '4': '未来科技',
  '5': '国画古风',
  '6': '将军百战',
  '7': '炫彩卡通',
  '8': '清雅国风',
  '9': '喜迎新年',
}

const selectedStyleIndex = ref<string>( '-1' )
const resultImageUrl = ref<string>()
const visible = ref(false)
const taskId = ref<string>()
const progress = ref<number>(0)
let progressTimer: NodeJS.Timeout | null = null
let pollingTimer: NodeJS.Timeout | null = null

// 接口定义
interface Props {
  picture?: API.PictureVO
  spaceId?: number
  styleIndex?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()

// 打开/关闭弹窗
const openModal = () => { visible.value = true }
const closeModal = () => { visible.value = false }
defineExpose({ openModal })

// 进度条动画
const startProgressTimer = () => {
  progress.value = 0
  progressTimer = setInterval(() => {
    if (progress.value < 99) progress.value += 10
    else clearInterval(progressTimer!)
  }, 1000)
}

const clearProgressTimer = () => {
  progressTimer && clearInterval(progressTimer)
  progressTimer = null
}

// 创建任务
const createTask = async () => {
  if (!props.picture?.id) return
  const res = await createImageRestyleTaskUsingPost({
    image_url: props.picture.url,
    style_index: selectedStyleIndex.value,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('创建任务成功，请耐心等待')
    taskId.value = res.data.data.output.taskId
    startProgressTimer()
    startPolling()
  } else {
    message.error(`创建任务失败：${res.data.message}`)
  }
}

// 轮询任务状态
const startPolling = () => {
  if (!taskId.value) return
  pollingTimer = setInterval(async () => {
    try {
      const res = await getImageRestyleTaskUsingGet({ taskId: taskId.value })
      if (res.data.code === 0 && res.data.data) {
        const taskResult = res.data.data.output
        if (taskResult.taskStatus === 'SUCCEEDED') {
          resultImageUrl.value = taskResult.results[0].url
          message.success('风格重塑成功')
          clearPolling()
          clearProgressTimer()
          progress.value = 100
        } else if (taskResult.taskStatus === 'FAILED') {
          message.error('任务失败，请重试')
          clearPolling()
          progress.value = 100
        }
      }
    } catch (error) {
      console.error('轮询失败:', error)
      message.error('检测任务状态失败，请稍后重试')
      clearPolling()
      progress.value = 100
    }
  }, 3000)
}

const clearPolling = () => {
  pollingTimer && clearInterval(pollingTimer)
  pollingTimer = null
  taskId.value = null
}

onUnmounted(() => {
  clearPolling()
  clearProgressTimer()
})

// 上传结果
const uploadLoading = ref<boolean>(false)
const handleUpload = async () => {
  uploadLoading.value = true
  try {
    const params: API.PictureUploadRequest = {
      fileUrl: resultImageUrl.value!,
      spaceId: props.spaceId!,
    }
    if (props.picture) params.id = props.picture.id
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      message.success('上传成功')
      props.onSuccess?.(res.data.data)
      closeModal()
    } else {
      message.error(`上传失败：${res.data.message}`)
    }
  } finally {
    uploadLoading.value = false
  }
}

// 交互反馈
const handleButtonClick = (event: MouseEvent) => {
  const btn = event.target as HTMLButtonElement
  btn.style.transform = 'scale(0.98)'
  setTimeout(() => (btn.style.transform = 'scale(1)'), 200)
}

// 图片加载动画
const onImageLoad = () => {
  const images = document.querySelectorAll('.preview-image')
  images.forEach(img => {
    img.classList.add('loaded')
  })
}
</script>

<style scoped>
.image-out-painting {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
}

.content-container {
  padding: 32px;
}

.ant-modal-header {
  padding: 24px 32px;
  border-bottom: none;
  background: linear-gradient(135deg, #ffffff, #f5f5f5);
}

.image-column {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-container {
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  background: #f8f8f8;
  transition: all 0.3s;
  min-height: 300px;
}

.image-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.section-title {
  margin-bottom: 16px;
  color: #333;
  font-weight: 600;
}

.preview-image {
  max-width: 100%;
  height: auto;
  transition: transform 0.3s, opacity 0.3s;
  transform: scale(1.02);
  opacity: 0;
}

.preview-image.loaded {
  transform: scale(1);
  opacity: 1;
}

.loading-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #666;
}

.style-selector {
  margin: 24px 0;
}

.custom-select {
  border-radius: 16px;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-section {
  margin: 24px 0;
}

.button-group {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 24px;
}

.action-btn {
  padding: 0 32px;
  height: 48px;
  font-size: 16px;
  border-radius: 24px;
  transition: all 0.3s;
  background: linear-gradient(45deg, #6a11cb, #2557d8);
  border-color: transparent;
}

.action-btn:hover {
  opacity: 0.9;
}

.ant-btn-primary[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 暗色主题可选 */
/* .dark-mode {
  background: #1a1a1a;
  color: white;
} */
</style>
